package com.baymax.test.scene

import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.format
import kotlinx.datetime.format.FormatStringsInDatetimeFormats
import kotlinx.datetime.format.byUnicodePattern
import kotlinx.datetime.toLocalDateTime

typealias ILogger = (String?) -> Unit

class SimpleLogger(baseScene: BaseScene, parent: ViewGroup) :
    CoroutineScope by baseScene.lifecycleScope, ILogger {
    private val log: TextView = TextView(baseScene.sceneContext).also { tv ->
        tv.setOnClickListener {
            tv.text = ""
        }
        parent.addView(tv)
    }

    @OptIn(FormatStringsInDatetimeFormats::class)
    private val format = LocalDateTime.Format {
        byUnicodePattern("yyyy-MM-dd HH:mm:ss.SSS")
    }
    private val zone = TimeZone.currentSystemDefault()


    private fun logFun(string: String): Job {
        val t = Clock.System.now().toLocalDateTime(zone)
        return launch {
            log.append(" [${t.format(format)}] ")
            log.append(string)
            log.append("\n")
        }
    }

    override fun invoke(p1: String?) {
        logFun(string = p1 ?: "null")
    }

}

fun BaseScene.installLogger(parent: ViewGroup): ILogger {
    return SimpleLogger(this, parent)
}